var BUILDINGS = require('../Utils/enums.js').BUILDINGS;

function newBuilding(id, heroId, type, posRow, posCol) {
    var curCapacity;
    switch(type) {
        case BUILDINGS.SILO:
            curCapacity = 50;
            break;
        case BUILDINGS.BARN:
            curCapacity = 250;
            break;
        case BUILDINGS.COLDSTORAGE:
            curCapacity = 300;
            break;
        default :
            break;
    }
    return {
        id: id,
        //pos = pos de la startTile
        pos: {
            row: posRow,
            col: posCol
        },
        stock: [],
        capacity: curCapacity,
        type : type,
        heroId: heroId
    }
}

//return null or index of the crop in hero's crops list
function isBuildingFound(hero, cl_building) {
    var buildingIndex = null;

    for(var index = 0; index < hero.buildings.length; index++) {
        if( (hero.buildings[index].pos.row == cl_building.pos.row)
            &&
            (hero.buildings[index].pos.col == cl_building.pos.col) ) {
            buildingIndex = index;
        }
    }

    return buildingIndex;
}

function createBuilding(hero, cl_building, callback) {
    hero.buildings[hero.buildings.length] = newBuilding(hero.buildings.length + 1, hero._id,
        cl_building.type, cl_building.pos.row, cl_building.pos.col);

    var curBuilding = hero.buildings[hero.buildings.length - 1];

    hero.markModified('buildings');
    hero.save(function(err) {
        if(err) console.log(err.message);
        else {
            console.log('building created for hero '+hero.name);
            callback(curBuilding);
        }
    })
}

//TODO handle delete ?
function updBuilding(hero, building, index, callback) {
    var curBuilding = hero.buildings[index];
        curBuilding.stock = building.stock;
        curBuilding.capacity = building.capacity;

    hero.markModified('buildings');
    hero.save(function(err) {
        if(err) console.log(err.message);
        else {
            console.log('building updated for hero : '+hero.name);
            callback(curBuilding);
        }
    });
}

exports.isBuildingFound = isBuildingFound;
exports.createBuilding = createBuilding;
exports.updBuilding = updBuilding;

